import React, { useState } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Input, 
  Select, 
  Row, 
  Col, 
  Statistic,
  Progress,
  Tooltip,
  Modal,
  Form,
  message
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined,
  EyeOutlined,
  LineChartOutlined,
  UserOutlined,
  HeartOutlined,
  MessageOutlined,
  ShareAltOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { Search } = Input;

interface Competitor {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  followers: number;
  following: number;
  posts: number;
  likes: number;
  comments: number;
  shares: number;
  engagementRate: number;
  category: string;
  lastUpdated: string;
  status: 'tracking' | 'paused';
}

const Competitor: React.FC = () => {
  const [competitors, setCompetitors] = useState<Competitor[]>([
    {
      id: '1',
      username: 'competitor1',
      nickname: '竞品账号1',
      avatar: '',
      followers: 50000,
      following: 200,
      posts: 150,
      likes: 25000,
      comments: 1200,
      shares: 800,
      engagementRate: 5.2,
      category: '美妆',
      lastUpdated: '2024-01-15 14:30:00',
      status: 'tracking'
    },
    {
      id: '2',
      username: 'competitor2',
      nickname: '竞品账号2',
      avatar: '',
      followers: 30000,
      following: 150,
      posts: 89,
      likes: 18000,
      comments: 950,
      shares: 600,
      engagementRate: 6.1,
      category: '时尚',
      lastUpdated: '2024-01-15 12:15:00',
      status: 'tracking'
    }
  ]);

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();

  const getStatusTag = (status: string) => {
    return status === 'tracking' 
      ? <Tag color="green">跟踪中</Tag>
      : <Tag color="orange">已暂停</Tag>;
  };

  const getEngagementColor = (rate: number) => {
    if (rate >= 5) return 'green';
    if (rate >= 3) return 'orange';
    return 'red';
  };

  const columns = [
    {
      title: '账号信息',
      key: 'account',
      render: (record: Competitor) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{ 
            width: 40, 
            height: 40, 
            borderRadius: '50%', 
            backgroundColor: '#f0f0f0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: 12
          }}>
            <UserOutlined />
          </div>
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.nickname}</div>
            <div style={{ color: '#666', fontSize: '12px' }}>@{record.username}</div>
          </div>
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '粉丝数',
      dataIndex: 'followers',
      key: 'followers',
      render: (value: number) => value.toLocaleString(),
      sorter: (a: Competitor, b: Competitor) => a.followers - b.followers,
    },
    {
      title: '互动率',
      key: 'engagement',
      render: (record: Competitor) => (
        <div>
          <div style={{ color: getEngagementColor(record.engagementRate) }}>
            {record.engagementRate}%
          </div>
          <Progress 
            percent={record.engagementRate} 
            size="small" 
            strokeColor={getEngagementColor(record.engagementRate)}
            showInfo={false}
          />
        </div>
      ),
      sorter: (a: Competitor, b: Competitor) => a.engagementRate - b.engagementRate,
    },
    {
      title: '数据统计',
      key: 'stats',
      render: (record: Competitor) => (
        <div style={{ fontSize: '12px' }}>
          <div>笔记: {record.posts}</div>
          <div>点赞: {record.likes.toLocaleString()}</div>
          <div>评论: {record.comments.toLocaleString()}</div>
          <div>分享: {record.shares.toLocaleString()}</div>
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      render: (record: Competitor) => getStatusTag(record.status),
    },
    {
      title: '最后更新',
      dataIndex: 'lastUpdated',
      key: 'lastUpdated',
    },
    {
      title: '操作',
      key: 'action',
      render: (record: Competitor) => (
        <Space>
          <Tooltip title="查看详情">
            <Button type="text" icon={<EyeOutlined />} size="small" />
          </Tooltip>
          <Tooltip title="数据分析">
            <Button type="text" icon={<LineChartOutlined />} size="small" />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleAdd = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const newCompetitor: Competitor = {
        id: Date.now().toString(),
        ...values,
        avatar: '',
        followers: 0,
        following: 0,
        posts: 0,
        likes: 0,
        comments: 0,
        shares: 0,
        engagementRate: 0,
        lastUpdated: new Date().toLocaleString(),
        status: 'tracking'
      };
      setCompetitors([...competitors, newCompetitor]);
      message.success('竞品账号添加成功');
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const totalFollowers = competitors.reduce((sum, item) => sum + item.followers, 0);
  const avgEngagement = competitors.reduce((sum, item) => sum + item.engagementRate, 0) / competitors.length;

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="跟踪账号数"
              value={competitors.length}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总粉丝数"
              value={totalFollowers}
              formatter={(value) => `${(value as number / 10000).toFixed(1)}万`}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均互动率"
              value={avgEngagement}
              precision={1}
              suffix="%"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总笔记数"
              value={competitors.reduce((sum, item) => sum + item.posts, 0)}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和操作栏 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <Search
              placeholder="搜索竞品账号"
              allowClear
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择分类"
              style={{ width: '100%' }}
              allowClear
            >
              <Option value="美妆">美妆</Option>
              <Option value="时尚">时尚</Option>
              <Option value="美食">美食</Option>
              <Option value="旅行">旅行</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="状态筛选"
              style={{ width: '100%' }}
              allowClear
            >
              <Option value="tracking">跟踪中</Option>
              <Option value="paused">已暂停</Option>
            </Select>
          </Col>
          <Col span={8} style={{ textAlign: 'right' }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              添加竞品
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <Card title="竞品账号列表">
        <Table
          columns={columns}
          dataSource={competitors}
          rowKey="id"
          pagination={{
            total: competitors.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加竞品模态框 */}
      <Modal
        title="添加竞品账号"
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入小红书用户名" />
          </Form.Item>
          
          <Form.Item
            name="nickname"
            label="昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              <Option value="美妆">美妆</Option>
              <Option value="时尚">时尚</Option>
              <Option value="美食">美食</Option>
              <Option value="旅行">旅行</Option>
              <Option value="生活">生活</Option>
              <Option value="数码">数码</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Competitor; 